package cn.wit.summit.chwan.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.dto.NoticeCommitDataBean;
import cn.wit.summit.chwan.models.event.EnergyEvent;
import cn.wit.summit.chwan.models.request.CreateCommentRequest;
import cn.wit.summit.chwan.models.request.GetCommentTokenRequest;
import cn.wit.summit.chwan.models.response.CreateCommentResponse;
import cn.wit.summit.chwan.models.response.GetCommentTokenResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.net.BuildRequestUtils;
import cn.wit.summit.chwan.net.NetCallBack;
import cn.wit.summit.chwan.net.okhttplib.HttpInfo;
import cn.wit.summit.chwan.net.okhttplib.OkHttpUtil;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.activity.CommentDetailActivity;
import cn.wit.summit.chwan.ui.activity.NoticeActivity;
import cn.wit.summit.chwan.ui.activity.ThumbsActivity;
import cn.wit.summit.chwan.utils.AESUtils;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.DateUtils;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringToUnicodeUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.widgets.ClearEditText;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import retrofit2.Retrofit;

/**
 * Created by pengsk on 2018/4/19.
 * 通知点评部分
 */

public class NoticeCommentFragment extends Fragment {

    RecyclerView recvcleView;
    List<CommentMainBean> datas = new ArrayList<>();
    LayoutInflater inflater;
    Activity context;
    static final int HEADTYPE = 1;
    static final int CONTENT = 2;
    static final int ORGINAL = 3;
    static final int REPLYCONTENT = 4;
    int from;
    RecyclerView recyclerView;
    SmartRefreshLayout refreshLayout;
    LinearLayout thumbslayout;
    LinearLayout inputLl;
    TextView redTips;

    public FrameLayout root_content_null_ll;
    public TextView retryText;
    public ImageView retryImg;
    ClearEditText editUserComment;
    private int pn = 1;
    private String replyContent;
    NoticeActivity activity;

    private RetrofitManager retrofitManager;
    private Retrofit retrofitComment;
    private ApiUtil apiComment;
    private Retrofit retrofit;
    private ApiUtil api;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.notice_comment_layout, container, false);
        recvcleView = view.findViewById(R.id.recyclerView);
        thumbslayout = view.findViewById(R.id.thumbslayout);
        inputLl = view.findViewById(R.id.inputLl);
        editUserComment = view.findViewById(R.id.edit_user_comment);
        redTips = view.findViewById(R.id.redTips);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofitComment = retrofitManager.getCommentRetrofit();
        apiComment = retrofitComment.create(ApiUtil.class);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        root_content_null_ll = (FrameLayout) view.findViewById(R.id.root_content_null_ll);
        retryText = view.findViewById(R.id.retryText);
        retryImg = view.findViewById(R.id.retryImg);
        context = getActivity();
        activity = (NoticeActivity) getActivity();
        if (activity.surplusNumberBean != null) {
            if (activity.surplusNumberBean.getPraise_surplus_number() > 0) {
                redTips.setVisibility(View.VISIBLE);
            } else {
                redTips.setVisibility(View.GONE);
            }
        }
        initView(view);
        getData();
        return view;
    }

    private void getData() {
        if (NetWorkUtils.isNetworkConnected(context)) {
            api.getNoticeCommitData(AccountUtil.getInstance().getUid(), AccountUtil.getInstance().getToken(), pn)
                    .enqueue(new MyCallback<ResponseBase<List<NoticeCommitDataBean>>>() {
                        @Override
                        public void onSuccess(ResponseBase<List<NoticeCommitDataBean>> model) {
                            List<NoticeCommitDataBean> data = model.getData_info();
                            if (data == null) {
                                refreshLayout.finishRefresh();
                                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                if (datas.size() == 0) {
                                    root_content_null_ll.setVisibility(View.VISIBLE);
                                    retryText.setText("暂无相关信息!");
                                }
                                return;
                            }
                            if (pn == 1) {
                                datas.clear();

                                refreshLayout.finishRefresh();
                                refreshLayout.setNoMoreData(false);
                                refreshLayout.finishLoadMore();
                            }
                            if (data.size() == 0) {
                                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                            } else {
                                refreshLayout.finishLoadMore();
                                pn++;
                            }

                            for (NoticeCommitDataBean dataBean : data) {
                                dataBean.setCurrent_reply_text(getNotEmu(dataBean.getCurrent_reply_text()));
                                dataBean.setCurrent_reply_title(getNotEmu(dataBean.getCurrent_reply_title()));
                                dataBean.setOriginal_text(getNotEmu(dataBean.getOriginal_text()));
                                datas.add(new CommentMainBean(dataBean, 1));
                                if (dataBean.getReply_sub() != null)
                                    datas.add(new CommentMainBean(dataBean, 4));
                                datas.add(new CommentMainBean(dataBean, 2));
                                datas.add(new CommentMainBean(dataBean, 3));
                            }
                            adapter.notifyDataSetChanged();
                            if (datas.size() == 0) {
                                root_content_null_ll.setVisibility(View.VISIBLE);
                                refreshLayout.setVisibility(View.GONE);
                                retryText.setText("暂无相关信息!");
                            } else {
                                root_content_null_ll.setVisibility(View.GONE);
                                refreshLayout.setVisibility(View.VISIBLE);

                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            ToastUtils.getInstance(context).showToastSystem(msg);
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMore();
                        }
                    });
        } else {
            root_content_null_ll.setVisibility(View.VISIBLE);
            retryImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    root_content_null_ll.setVisibility(View.GONE);
                    getData();
                }
            });
        }


    }

    private String getNotEmu(String str) {
        if (str.contains("EM-")) {
            try {
                str = StringToUnicodeUtil.unicode2String(str);
                return str;
            } catch (Exception e) {
                LogUtils.e("---m---e.getMessage():" + e.getMessage());
            }
        }
        return str;
    }

    public class CommentMainBean {
        public NoticeCommitDataBean object;
        public int type;

        public CommentMainBean(NoticeCommitDataBean object, int type) {
            this.object = object;
            this.type = type;
        }
    }

    public static NoticeCommentFragment newInstance() {
        Bundle args = new Bundle();
        NoticeCommentFragment fragment = new NoticeCommentFragment();
        fragment.setArguments(args);
        return fragment;
    }

    MYUpdateAdapter adapter = null;

    private void initView(View view) {
        recyclerView = view.findViewById(R.id.recyclerView);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        inflater = LayoutInflater.from(context);
        recvcleView.setLayoutManager(new LinearLayoutManager(context));
        adapter = new MYUpdateAdapter();
        //添加自定义分割线
//        DividerItemDecoration divider = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);x
//        divider.setDrawable(ContextCompat.getDrawable(context, R.drawable.item_driver_h));
//        recvcleView.addItemDecoration(divider);
        recvcleView.setAdapter(adapter);
        refreshLayout.autoLoadMore();
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getData();
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pn = 1;
                getData();
            }
        });
        thumbslayout.setVisibility(View.VISIBLE);
        thumbslayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                redTips.setVisibility(View.GONE);
                if (activity.surplusNumberBean != null)
                    activity.surplusNumberBean.setPraise_surplus_number(0);
                Intent intentB = new Intent("com.send.message.hasClickPrase");
                context.sendBroadcast(intentB);
                Intent intent = new Intent(getContext(), ThumbsActivity.class);
                startActivity(intent);
            }
        });
    }


    class VHHead extends RecyclerView.ViewHolder {

        SimpleDraweeView userIcon;
        TextView userName;
        TextView reply;
        TextView time;
        View view;

        public VHHead(View itemView) {
            super(itemView);
            userIcon = itemView.findViewById(R.id.userIcon);
            userName = itemView.findViewById(R.id.userName);
            reply = itemView.findViewById(R.id.reply);
            time = itemView.findViewById(R.id.time);
            view = itemView;
        }
    }

    class VHContent extends RecyclerView.ViewHolder {

        TextView content;
        View view;

        public VHContent(View itemView) {
            super(itemView);
            content = itemView.findViewById(R.id.content);
            view = itemView;
        }
    }

    class VHOrginal extends RecyclerView.ViewHolder {

        TextView orignal;
        View view;

        public VHOrginal(View itemView) {
            super(itemView);
            orignal = itemView.findViewById(R.id.orignal);
            view = itemView;
        }
    }

    class VHReply extends RecyclerView.ViewHolder {

        TextView replyContent;
        View view;

        public VHReply(View itemView) {
            super(itemView);
            replyContent = itemView.findViewById(R.id.replyContent);
            view = itemView;
        }
    }

    class MYUpdateAdapter extends RecyclerView.Adapter {

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder holder = null;
            View view = null;
            switch (viewType) {
                case 1:
                    view = inflater.inflate(R.layout.notice_comment_list_head_layout, parent, false);
                    holder = new VHHead(view);
                    break;
                case 2:

                    view = inflater.inflate(R.layout.notice_comment_list_content_layout, parent, false);
                    holder = new VHContent(view);
                    break;
                case 3:

                    view = inflater.inflate(R.layout.notice_comment_list_orignal_layout, parent, false);
                    holder = new VHOrginal(view);
                    break;
                case 4:

                    view = inflater.inflate(R.layout.notice_comment_list_reply_layout, parent, false);
                    holder = new VHReply(view);
                    break;
            }
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
            int type = getItemViewType(position);
            final NoticeCommitDataBean dataBean = datas.get(position).object;
            switch (type) {
                case 1:
                    VHHead vhHead = (VHHead) holder;
                    vhHead.userIcon.setImageURI(Uri.parse(dataBean.getCurrent_reply_user_ico()));
                    vhHead.userName.setText(dataBean.getCurrent_reply_title());
                    long time = dataBean.getCurrent_reply_time() * 1000l;
                    if (DateUtils.isToday(time)) {
                        vhHead.time.setText(DateUtils.getTimeHM(time));
                    } else if (DateUtils.isToYear(time)) {
                        vhHead.time.setText(DateUtils.getTimeMDHM(time));
                    } else {
                        vhHead.time.setText(DateUtils.getTimeYMDHM(time));
                    }
                    vhHead.view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            bottomDialog(dataBean);
                        }
                    });
                    break;
                case 2:
                    VHContent vhContent = (VHContent) holder;
                    String reply = dataBean.getCurrent_reply_text();
                    try {
                        if (reply.contains("@"))
                            reply = reply.split(":")[1];
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    vhContent.content.setText(reply);
                    vhContent.view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            bottomDialog(dataBean);
                        }
                    });
                    break;
                case 3:
                    VHOrginal vhOrginal = (VHOrginal) holder;
                    vhOrginal.orignal.setText("原文：" + dataBean.getOriginal_text());
                    vhOrginal.view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(context, CommentDetailActivity.class);
                            intent.putExtra("commentId", dataBean.getOriginal_text_id() + "");
                            intent.putExtra("gameid", dataBean.getGame_id());
                            startActivity(intent);

                        }
                    });
                    break;
                case 4:
                    VHReply vhReply = (VHReply) holder;
                    String message = dataBean.getReply_sub().getReply_text();
//                    if (message.contains(":")){
//                    String[] data = message.split(":");
//                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
//                        vhReply.replyContent.setText(Html.fromHtml("<font color=\"#5791F7\">" + data[0] + ":</font>" + data[1], Html.FROM_HTML_MODE_LEGACY));
//                    } else {
//                        vhReply.replyContent.setText(Html.fromHtml("<font color=\"#5791F7\">" + data[0] + ":</font>" + data[1]));
//                    }
//                    vhReply.view.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            bottomDialog(dataBean);
//                        }
//                    });
//
//                    }else {
                    vhReply.replyContent.setText(message);
//                    }
                    break;
            }


        }

        @Override
        public int getItemViewType(int position) {
//            CommentMainBean mainBean=games.get(position);
            return datas.get(position).type;
        }

        @Override
        public int getItemCount() {
            return datas.size();
        }
    }

    void bottomDialog(NoticeCommitDataBean dataBean) {

        showPopupWindow(dataBean);
    }

    private void showPopupWindow(final NoticeCommitDataBean dataBean) {
        View contentView = LayoutInflater.from(context).inflate(R.layout.appointment_pay_popwindow_page, null);
        mPopWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);

        final EditText edit = contentView.findViewById(R.id.edit);
        edit.setHint("回复点评内容");

        final LinearLayout ll_root = contentView.findViewById(R.id.toot);
        final TextView tv_que = contentView.findViewById(R.id.tv_confirm);
        ll_root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
            }
        });
        tv_que.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
                replyContent = edit.getText().toString();
                replyComment(dataBean);
            }
        });
        edit.setFocusable(true);
        mPopWindow.setFocusable(true);
        edit.setFocusableInTouchMode(true);
        edit.setFocusable(true);
        edit.requestFocus();
        mPopWindow.setOutsideTouchable(true);
        InputMethodManager m = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        m.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
        final View decorView = context.getWindow().getDecorView();
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);
                int displayHight = rect.bottom - rect.top;
                int hight = decorView.getHeight();
                if (displayHight > hight / 3 * 2) {
                    if (isc == true) {
                        mPopWindow.dismiss();
                        isc = false;
                    }
                } else {
                    isc = true;
                }
            }
        });
        //显示PopupWindow
        View rootview = LayoutInflater.from(context).inflate(R.layout.activity_setting, null);
        showPopmenu(rootview);
    }

    boolean isc = false;

    PopupWindow mPopWindow;

    private void showPopmenu(View rootview) {
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = context.getWindow().getAttributes();
                lp.alpha = 1f;
                context.getWindow().setAttributes(lp);
            }
        });
        // 显示窗口位置
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = 0.4f;
        context.getWindow().setAttributes(lp);
    }


    private void replyComment(NoticeCommitDataBean dataBean) {
        if (AccountUtil.getInstance().getUid() == 0) {
            IntentUtil.getInstance().goLoginActivity(context);
            return;
        }
        if (replyContent.length() == 0) {
            showToast("不能发表空字符串");
            return;
        }
        if (replyContent.length() < 3 || replyContent.length() > 800) {
            showToast(getResources().getString(R.string.comment_sub_str));
            return;
        }
        comentToken = PreferenceUtil.getPreferences(context, PreferenceUtil.PRE_COMMENT_TOKEN);
        if (StringUtils.isEmpty(comentToken) || comentToken.equals("-1")) {
            getCommentToken(dataBean);
        } else {
            toCreateComment(dataBean.getOriginal_text_id() + "", replyContent, android.os.Build.MODEL
                    , dataBean.getCurrent_reply_text_uid() + "", dataBean.getCurrent_reply_title(), dataBean.getCurrent_reply_text_id() + "", 1, dataBean.getGame_id());
        }

    }

    private void showToast(String msg) {
        ToastUtils.getInstance(context).showToastSystem(msg);
    }

    private void toCreateComment(String replyMainCommentId, String replyContent, String model
            , String replyUid, String replyUserName, String replyCommentId, int replyPn, String gameid) {
        AccountBean accountBean = AccountUtil.getInstance().getAccountData();

        CreateCommentRequest request = retrofitManager.replayCommentRequest(comentToken, gameid
                , accountBean.getUid() + "", accountBean.getToken(), accountBean.getAvatar(), accountBean.getNickname()
                , replyContent, replyCommentId, replyUserName, replyUid, 2, replyMainCommentId, replyPn,false);
        apiComment.createComment(request).enqueue(new MyCallback<ResponseBase<CreateCommentResponse>>() {
            @Override
            public void onSuccess(ResponseBase<CreateCommentResponse> model) {
                CreateCommentResponse data = model.getData_info();
                if (data != null && data.getAdd_comment_energy() > 0) {
                    EnergyEvent energyEvent = new EnergyEvent();
                    energyEvent.setNumber(data.getAdd_comment_energy());
                    EventBus.getDefault().post(energyEvent);
                }
                ToastUtils.getInstance(context).showToastSystem("回复成功！");
            }

            @Override
            public void onFailure(int code, String msg) {
                ToastUtils.getInstance(context).showToastSystem(msg);
            }
        });
    }

    public String comentToken;

    private void getCommentToken(final NoticeCommitDataBean dataBean) {
        GetCommentTokenRequest tempRequest = retrofitManager.getCommentTokenRequest();
        apiComment.getCommentToken(tempRequest).enqueue(new MyCallback<ResponseBase<GetCommentTokenResponse>>() {
            @Override
            public void onSuccess(ResponseBase<GetCommentTokenResponse> model) {
                GetCommentTokenResponse data = model.getData_info();
                String token = AESUtils.encrypt4Comment(data.getToken() + "|" + data.getTimes());
                comentToken = token;
                toCreateComment(dataBean.getOriginal_text_id() + "", replyContent, android.os.Build.MODEL
                        , dataBean.getCurrent_reply_text_uid() + "", dataBean.getCurrent_reply_title(), dataBean.getCurrent_reply_text_id() + "", 1, dataBean.getGame_id());

                PreferenceUtil.savePreference(context, PreferenceUtil.PRE_COMMENT_TOKEN, token);
                PreferenceUtil.saveLongPreference(context, PreferenceUtil.PRE_COMMENT_TOKEN_TIME, data.getTimes());
            }

            @Override
            public void onFailure(int code, String msg) {
                PreferenceUtil.savePreference(context, PreferenceUtil.PRE_COMMENT_TOKEN, "-1");
                showToast(msg);
            }
        });
    }
}
